import { createRouter, createWebHistory } from 'vue-router';
import Layout from'@/layouts/index';
import { useUserStore, useRoutersStore, useTokenStore } from '@/stores';

// 通用路由
const constantRoutes = [
    {
        name:'Login',
        path: '/login',
        component:()=>import("@/views/login/login"),
        hidden:true,
    },

    {
        path: '/',
        redirect:'index',
        component:Layout,
        hidden:true,
        meta:{title:"首页"},
        children:[
            {
                name: 'Index',
                path: 'index',
                hidden: false,
                component:()=> import('@/views/index/index'),
                meta:{title:"首页"},
            },
        ],
    },
    {
        path: '/404',
        component:()=>import("@/views/error/404"),
        hidden:true,
    },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: constantRoutes
})


const whiteList = ['/login']
router.beforeEach(async(to, from, next) => {
    const tokenStore = useTokenStore();
    if(tokenStore.token){
        if(to.name === 'Login'){
            next({path:'/'})
        }else{
            const userStore = useUserStore();
            if(userStore.user.roles.length === 0){
                try {
                    await userStore.userInfo()
                    const routers = useRoutersStore();
                    await routers.saveRouters();
                    next({...to,replace:true})
                } catch (error) {
                    // 保存说明token真正过期,清空
                    await userStore.clearUser();
                    await tokenStore.clearToken();
                    next({path:'/login'})
                }
            }else{
                next()
            }
        }
    }else{
        if(whiteList.includes(to.path)){
            next()
        }else{
            next(`/login?redirect=${to.path}`)
            // next({path:'/login'})
        }
    }
})

export default router